package com.demo.security.custom.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.demo.security.custom.ex.InvalidVerifyCodeException;
import com.demo.security.model.Result;
import com.demo.security.utils.ResponseUtils;

/**
 * 鉴权失败的处理器
 * 
 * @author OL
 *
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
        log.info("登录失败: {}, {}", ex.getClass(), ex.getMessage());
        String msg = "登录失败: ";
        if (ex instanceof BadCredentialsException || ex instanceof UsernameNotFoundException || ex instanceof InternalAuthenticationServiceException) {
            msg += "用户名或密码错误";
        } else if (ex instanceof LockedException) {
            msg += "用户已锁定";
        } else if (ex instanceof CredentialsExpiredException) {
            msg += "用户凭据已过期";
        } else if (ex instanceof AccountExpiredException) {
            msg += "用户已过期";
        } else if (ex instanceof DisabledException) {
            msg += "用户已禁用";
        } else if (ex instanceof InvalidVerifyCodeException) {
            msg += "验证码错误";
        }
        Result<Object> result = Result.failure(403, msg);
        ResponseUtils.writeJson(response, result);
    }
}
